<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 130px">
            <el-option label="退货单号" value="return_no"></el-option>
            <el-option label="来源单号" value="source_no"></el-option>
            <el-option label="采购单号" value="purchase_no"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" @search="query" class="w-60" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.skuInfo.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <VBatchInput v-model="form.skuInfo.value" @search="query" class="w-60" />
        </VGroup>
        <VSelect v-model="form.return_status" placeholder="退货状态" :options="options.return_status || []" multiple
          collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.return_type" placeholder="来源类型" :options="options.return_type || []" multiple collapse-tags
          filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple
          collapse-tags clearable filterable />
        <VSelect v-model="form.return_warehouse" placeholder="退货仓库" type="warehouse156" multiple collapse-tags filterable
          clearable style="min-width: 160px" />
        <VSelect v-model="form.return_method" placeholder="退货方式" :options="options.return_method || []" multiple
          collapse-tags filterable clearable style="min-width: 160px" />
        <VCascader v-model="form.create_user_id" placeholder="申请人" multiple collapse-tags filterable clearable
          style="min-width: 160px" />
        <VCascader v-model="form.warehouse_process_user_id" placeholder="仓库处理人" multiple collapse-tags filterable
          clearable style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 126px">
            <el-option label="单据生成时间" value="create_time"></el-option>
            <el-option label="退货时间" value="return_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VAudit auth="/purchase/manage/return/audit" field="rg_id" url="/v1/purchase/return-goods/batch-audit"
          :tableRef="tableRef" :list="[{ label: '审核', value: 2 }]" @success="query" />
        <VButton auth="/purchase/manage/return/cancel" @click="handleBatch('cancel', row)">批量作废</VButton>
        <VExport auth="/purchase/manage/return/export" name="return-goods" mainKey="rg_id" :tableRef="tableRef" task
          class="ml-auto" />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <VLog ref="logRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'


import { getOption} from '@/api/public'
import { resMessage} from '@/utils/res'
import { ElMessage, ElMessageBox } from 'element-plus'

const baseName = 'return_goods'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 添加
const addRef = ref()

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const contractRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const rg_ids = selection.map(d => d.rg_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    cancel: () => {
      ElMessageBox.confirm('是否确认作废？', '取消', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.cancel({ rg_ids }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
  }
  handle[name]()
}

// 单行操作
const handleRow = (name, row, rowIndex) => {
  const { rg_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    look: () => {
      addRef?.value.open(rg_id, true)
    },
    edit: () => {
      addRef?.value.open(rg_id)
    },
    submit: () => {
      showLoading()
      api.submit({ rg_id }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
    cancel: () => {
      ElMessageBox.confirm('是否确认作废？', '取消', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.cancel({ rg_ids: [rg_id] }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, rg_id })
    },
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 92 },
  showHeaderOverflow: false,
  formConfig: {
    data: {
      input: { type: 'return_no', value: '' },
      skuInfo: { type: 'sku', value: '' },
      dateRange: { type: 'create_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    {
      width: 150, slots: {
        header: () => <div>退货单号<br/>采购单号</div>,
        default: ({ row, rowIndex }) => <div>
          <VText value={row.return_no} type='link' onClick={() => handleRow('look', row)}></VText>
          <VMore key={rowIndex}>
            {{
              default: (line) => (row.purchase_no || []).map(d => <div class='w-full'>
                <VText value={d} line={line} />
              </div>)
            }}
          </VMore>
        </div>
      }
    },
    {
      width: 200, slots: {
        header: () => <div>供应商信息</div>,
        default: ({ row }) => <div>
          <VText title='供应商' value={row.supplier_name} />
          <VText title='供应商id' value={row.supplier_code} />
          <VText title='结算方式' value={row.period_name} />
        </div>
      }
    },
    {
      width: 100, slots: {
        header: () => <div>来源类型</div>,
        default: ({ row }) => <VText value={row.return_type_name} />
      }
    },
    {
      width: 150, slots: {
        header: () => <div>来源单号</div>,
        default: ({ row, rowIndex }) => {
          return <VMore key={rowIndex}>
            {{
              default: (line) => (row.source_no || []).map(d => <div class='w-full'>
                <VText value={d} line={line} />
              </div>)
            }}
          </VMore>
        }
      }
    },
    {
      width: 120, slots: {
        header: () => <div>退货单状态</div>,
        default: ({ row }) => <VText value={row.return_status_name} />
      }
    },
    {
      width: 100, slots: {
        header: () => <div>sku</div>,
        default: ({ row, rowIndex }) => {
          return <VMore key={rowIndex}>
            {{
              default: (line) => (row.sku || []).map(d => <div class='w-full'>
                <VText value={d} line={line} />
              </div>)
            }}
          </VMore>
        }
      }
    },
    {
      title: '图片', width: 100, slots: {
        default: ({ row }) => <VImage src={row.main_img} size="80px"></VImage>
      }
    },
    {
      width: 120, slots: {
        header: () => <div>退货仓库</div>,
        default: ({ row }) => row.return_warehouse_name || '-'
      }
    },
    {
      width: 80, slots: {
        header: () => <div>退货数量</div>,
        default: ({ row }) => row.return_num || '-'
      }
    },
    {
      width: 80, slots: {
        header: () => <div>退货方式</div>,
        default: ({ row }) => row.return_method_name || '-'
      }
    },
    {
      width: 160, slots: {
        header: () => <div>快递公司<br />运单号</div>,
        default: ({ row }) => <div>
          <VText title='快递公司'>{row.tracking_company}</VText>
          <VText title='运单号'>{row.tracking_number}</VText>
        </div>
      }
    },
    {
      width: 80, slots: {
        header: () => <div>运费</div>,
        default: ({ row }) => row.tracking_price || '-'
      }
    },
    {
      width: 140, slots: {
        header: () => <div>退货地址</div>,
        default: ({ row }) => <VText value={row.return_address} line={3} />
      }
    },
    {
      width: 120, slots: {
        header: () => <div>退货备注</div>,
        default: ({ row }) => <VText value={row.remark} line={3} />
      }
    },
    {
      width: 170, slots: {
        header: () => <div>申请人<br />生成时间<br />审核人<br />审核时间</div>,
        default: ({ row }) => <div>
          <VText value={row.create_user} />
          <VText value={row.create_time} />
          <VText value={row.audit_user_name} />
          <VText value={row.audit_time} />
        </div>
      }
    },
    {
      width: 170, slots: {
        header: () => <div>仓库处理人员<br />退货时间</div>,
        default: ({ row }) => <div>
          <VText value={row.warehouse_process_user} />
          <VText value={row.return_time} />
        </div>
      }
    },
    {
      title: '操作', width: 100, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { return_status } = row
          // return_status	退货单状态 1待提交 2待审核 3待仓库处理 4已处理 5已驳回 6已作废
          return <div class='nm flex flex-wrap gap-x-2 gap-y-1'>
            <VButton auth="/purchase/manage/return/detail" link type="primary" onClick={() => handleRow('look', row, rowIndex)}>查看</VButton>
            {[1, 5].includes(return_status) ? <VButton auth="/purchase/manage/return/edit" link type="primary" onClick={() => handleRow('edit', row, rowIndex)}>编辑</VButton> : ''}
            {[1, 5].includes(return_status) ? <VButton auth="/purchase/manage/return/submit" link type="primary" onClick={() => handleRow('submit', row, rowIndex)}>提交</VButton> : ''}
            {[1, 5].includes(return_status) ? <VButton auth="/purchase/manage/return/cancel" link type="primary" onClick={() => handleRow('cancel', row, rowIndex)}>作废</VButton> : ''}
            <VButton auth="/purchase/manage/return/log" link type="primary" onClick={() => handleRow('log', row, rowIndex)}>日志</VButton>
          </div>
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>
  